package docks;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import com.google.android.maps.GeoPoint;

import android.app.ProgressDialog;
import android.content.Context;

import persistence.DataBaseController;

import utils.DataDownloader;
import utils.HTML;

public class DockAPIImpl implements DockAPI {

    private String xml;

    public List<Dock> getAllDocks() {

	return DataBaseController.getInstance().getAllDocks();
    }

    @Override
    public Dock getDockInfo(int dockid) {
	
	return DataBaseController.getInstance().getDock(dockid);
    }

    @Override
    public void setStarred(int dockid, boolean starred) {

    }

    @Override
    public List<Dock> getAllStarred() {

	return DataBaseController.getInstance().getAllStarred();
    }

    @Override
    public void refreshData(Hashtable<Integer, Dock> data) {
	
	try {
//	    
//	    DataDownloader dd = new DataDownloader();
//	    
//	    Hashtable<Integer, Dock> data = dd.download();
	    
	    for (Dock d: data.values()) {
		
		DataBaseController.getInstance().updateDock(d.getIdDock(), d.getFreeSlots(), d.getAvailableBikes());
	    }
	    
	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }

    @Override
    public List<Dock> getFullDocks() {
	
	return DataBaseController.getInstance().getFullDocks();
    }

    @Override
    public List<Dock> getHalfDocks() {
	
	return DataBaseController.getInstance().getHalfDocks();
    }

    @Override
    public List<Dock> getEmptyDocks() {
	
	return DataBaseController.getInstance().getEmptyDocks();
    }

    @Override
    public Dock getClosestDock(GeoPoint me, boolean park) {

	Dock ret = null;
	List<Dock> docks = null;
	if(park){ 
		docks = DataBaseController.getInstance().getNotFullDocks();
	}else{
		docks = DataBaseController.getInstance().getNotEmptyDocks();
	}
	double distance = -1;
	double tmp;
	
	GeoPoint p;
	
	for (Dock d : docks) {
	    
	    p = getPoint(d.getLongitude(),d.getLatitude());
	    tmp = euclideanDistance(me,p);
	    
	    if (distance == -1) {
		
		distance = tmp;
		ret = d;
	    } else if (tmp < distance) {
		
		distance = tmp;
		ret = d;
	    }
	}
	
	return ret;
    }
    
    private double euclideanDistance(GeoPoint a, GeoPoint b) {
	
	double distance, x, y;
	
	x = ( b.getLatitudeE6() - a.getLatitudeE6());
	x *= x;
	
	y = ( b.getLongitudeE6() - a.getLongitudeE6() );
	y *= y;
	
	distance = Math.sqrt(x+y);
	
	return distance;
    }
    
    private GeoPoint getPoint(double lat, double lon) {
	return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
    }
}
